{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "当读者习惯使用飞桨框架完成建模时，会发现程序呈现出“八股文”的形态。即不同的程序员使用不同模型解决不同任务的时候，他们编写的建模程序是极其相似的。虽然这在某些“极客”的眼里缺乏精彩，但从实用性的角度，这样的设计使建模者更关注需要解决的任务，而不是将精力投入在学习框架上。只要通过一个示例程序掌握使用飞桨的方法，编写实现不同任务的多种模型均变得十分容易。\n",
    "\n",
    "这点与Python的设计思想一致：对于某个特定功能，并不是实现方式越灵活、越多样越好，最好只有一种最符合“道”的最佳实现。“道”指的是如何人类的思维习惯，当程序员第一次看到Python的很多使用方式，感觉程序天然就应该如此实现。但相信我，不是所有的编程语言都具备这样合道的设计，很多编程语言的设计思路是人应该去理解机器的运作原理。同时，灵活意味着复杂，增加了程序员之间的沟通难度，也不适合现在工业化生产软件的现实。\n",
    "\n",
    "所以，飞桨设计的初衷不仅要易于学习，还期望使用者能够体会到它的美感和哲学，与人类最自然的认知和习惯相契合。\n",
    "\n",
    "本书中的案例覆盖经典的预测任务、推荐系统、计算机视觉和自然语言处理等主流应用场景，但所有的案例代码结构均完全一致，分为如下5个部分。\n",
    "- １. 数据处理：读取数据和预处理操作\n",
    "- ２. 模型设计：搭建神经网络结构\n",
    "- ３. 训练配置：优化器、学习率（寻解算法）\n",
    "- ４. 训练过程：循环调用训练过程，包括前向计算 + 计算损失（优化目标) + 后向传播\n",
    "- ５. 保存模型并测试：将训练好的模型保存\n",
    "\n",
    "下面我们使用飞桨框架，按照五个步骤重写房价预测的模型，体会下使用飞桨框架的感觉。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#加载飞桨、Numpy和相关类库\n",
    "import paddle\n",
    "import paddle.fluid as fluid\n",
    "import paddle.fluid.dygraph as dygraph\n",
    "from paddle.fluid.dygraph import FC\n",
    "import numpy as np\n",
    "import os\n",
    "import random"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 1. 数据处理\n",
    "\n",
    "\n",
    "这部分代码不依赖框架实现，与使用Python编写神经网络模型的代码相同，不再赘述。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def load_data():\n",
    "    # 从文件导入数据\n",
    "    datafile = './work/housing.data'\n",
    "    data = np.fromfile(datafile, sep=' ')\n",
    "\n",
    "    # 每条数据包括14项，其中前面13项是影响因素，第14项是相应的房屋价格中位数\n",
    "    feature_names = [ 'CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', \\\n",
    "                      'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV' ]\n",
    "    feature_num = len(feature_names)\n",
    "\n",
    "    # 将原始数据进行Reshape，变成[N, 14]这样的形状\n",
    "    data = data.reshape([data.shape[0] // feature_num, feature_num])\n",
    "\n",
    "    # 将原数据集拆分成训练集和测试集\n",
    "    # 这里使用80%的数据做训练，20%的数据做测试\n",
    "    # 测试集和训练集必须是没有交集的\n",
    "    ratio = 0.8\n",
    "    offset = int(data.shape[0] * ratio)\n",
    "    training_data = data[:offset]\n",
    "\n",
    "    # 计算train数据集的最大值，最小值，平均值\n",
    "    maximums, minimums, avgs = training_data.max(axis=0), training_data.min(axis=0), \\\n",
    "                                 training_data.sum(axis=0) / training_data.shape[0]\n",
    "    \n",
    "    # 记录数据的归一化参数，在预测时对数据做归一化\n",
    "    global max_values\n",
    "    global min_values\n",
    "    global avg_values\n",
    "    max_values = maximums\n",
    "    min_values = minimums\n",
    "    avg_values = avgs\n",
    "\n",
    "    # 对数据进行归一化处理\n",
    "    for i in range(feature_num):\n",
    "        #print(maximums[i], minimums[i], avgs[i])\n",
    "        data[:, i] = (data[:, i] - avgs[i]) / (maximums[i] - minimums[i])\n",
    "\n",
    "    # 训练集和测试集的划分比例\n",
    "    #ratio = 0.8\n",
    "    #offset = int(data.shape[0] * ratio)\n",
    "    training_data = data[:offset]\n",
    "    test_data = data[offset:]\n",
    "    return training_data, test_data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 2. 模型设计\n",
    "\n",
    "定义线性回归的网络结构，飞桨建议通过创建Python类的方式完成模型网络的定义。\n",
    "1. 在类的初始化函数中定义每一层网络的实现函数，这里我们定义了一层全连接层FC，模型结构和[1-2 节](https://aistudio.baidu.com/aistudio/projectdetail/186213)模型保持一致。\n",
    "2. 定义forward函数构建神经网络结构，实现前向计算过程，并返回预测结果，本例中返回的是房价预测结果。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class Regressor(fluid.dygraph.Layer):\n",
    "    def __init__(self, name_scope):\n",
    "        super(Regressor, self).__init__(name_scope)\n",
    "        name_scope = self.full_name()\n",
    "        # 定义一层全连接层，输出维度是1，激活函数为None，即不使用激活函数\n",
    "        self.fc = FC(name_scope, size=1, act=None)\n",
    "    \n",
    "    # 网络的前向计算函数\n",
    "    def forward(self, inputs):\n",
    "        x = self.fc(inputs)\n",
    "        return x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 3. 训练配置\n",
    "\n",
    "训练配置包括：\n",
    "1. 声明定义好的模型。\n",
    "2. 加载训练数据和测试数据。\n",
    "3. 设置优化算法和学习率，本次实验优化算法使用随机梯度下降[SGD](https://www.paddlepaddle.org.cn/documentation/docs/zh/api_cn/optimizer_cn/SGDOptimizer_cn.html#cn-api-fluid-optimizer-sgdoptimizer)，学习率使用 0.01。\n",
    "\n",
    "**说明：**  \n",
    "在之前基于Python实现神经网络模型的案例中，我们为实现梯度下降编写了大量代码，而使用飞桨框架可以大大简化这个过程。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 定义飞桨动态图的工作环境\n",
    "with fluid.dygraph.guard():\n",
    "    # 声明定义好的线性回归模型\n",
    "    model = Regressor(\"Regressor\")\n",
    "    # 开启模型训练模式\n",
    "    model.train()\n",
    "    # 加载数据\n",
    "    training_data, test_data = load_data()\n",
    "    # 定义优化算法，这里使用随机梯度下降-SGD\n",
    "    # 学习率设置为0.01\n",
    "    opt = fluid.optimizer.SGD(learning_rate=0.01)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "**注意：** 上述代码中，可以发现声明模型，定义优化器等都在with创建的[fluid.dygraph.guard()](https://www.paddlepaddle.org.cn/documentation/docs/zh/api_cn/dygraph_cn/guard_cn.html#guard)上下文环境中进行，可以理解为with fluid.dygraph.guard()创建了飞桨动态图的工作环境，在该环境下完成模型声明、数据转换、以及模型训练等操作。\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 4. 训练过程\n",
    "\n",
    "完成训练配置后即可启动训练过程。训练采用二层循环嵌套方式：\n",
    "- 内层循环负责整个数据集的一次遍历，遍历数据集采用分批次（batch）方式，假设数据集样本数量为1000，一个批次有10个样本，则遍历一次数据集的批次数量是1000/10=100，即内层循环需要循环100次；\n",
    "- 外层循环定义遍历数据集的次数，本次训练中外层循环10次，通过参数EPOCH_NUM设置；\n",
    "\n",
    "\n",
    "**说明**:  \n",
    "batch大小的选择会影响训练效果，batch过大会增大内存消耗，过小则每个batch的样本数据没有统计意义。本次训练数据集较小，我们设置batch为10。\n",
    "\n",
    "在每次内层循环都需要进行前向计算、损失函数计算和梯度反向传播三个步骤，计算的过程与Python编写的模型完全一致；\n",
    "\n",
    "1. 前向计算即将一个批次的样本数据灌入网络中，计算输出结果。\n",
    "2. 以前向计算结果和真实房价作为输入，通过损失函数[square_error_cost](https://www.paddlepaddle.org.cn/documentation/docs/zh/api_cn/layers_cn/square_error_cost_cn.html#square-error-cost)计算出损失函数值（Loss）。\n",
    "3. 执行梯度反向传播backward函数，即从后到前逐层计算每一层的梯度，并根据设置的优化算法更新参数（opt.minimize）。\n",
    "\n",
    "\n",
    "这个实现过程令人惊喜，前向计算、计算损失和反向传播梯度，每个操作居然只有1-2行代码即可实现！我们再也不用一点点的实现模型训练的细节，这就是使用飞桨框架的威力！"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 0, iter: 0, loss is: [0.36573568]\n",
      "epoch: 0, iter: 20, loss is: [0.33971325]\n",
      "epoch: 0, iter: 40, loss is: [0.5716193]\n",
      "epoch: 1, iter: 0, loss is: [0.33198822]\n",
      "epoch: 1, iter: 20, loss is: [0.32750577]\n",
      "epoch: 1, iter: 40, loss is: [0.20174979]\n",
      "epoch: 2, iter: 0, loss is: [0.21398032]\n",
      "epoch: 2, iter: 20, loss is: [0.15974538]\n",
      "epoch: 2, iter: 40, loss is: [0.08182637]\n",
      "epoch: 3, iter: 0, loss is: [0.13637844]\n",
      "epoch: 3, iter: 20, loss is: [0.07012554]\n",
      "epoch: 3, iter: 40, loss is: [0.12868139]\n",
      "epoch: 4, iter: 0, loss is: [0.11150487]\n",
      "epoch: 4, iter: 20, loss is: [0.12286273]\n",
      "epoch: 4, iter: 40, loss is: [0.28625053]\n",
      "epoch: 5, iter: 0, loss is: [0.12325518]\n",
      "epoch: 5, iter: 20, loss is: [0.05488824]\n",
      "epoch: 5, iter: 40, loss is: [0.04552042]\n",
      "epoch: 6, iter: 0, loss is: [0.0609853]\n",
      "epoch: 6, iter: 20, loss is: [0.09205151]\n",
      "epoch: 6, iter: 40, loss is: [0.08044842]\n",
      "epoch: 7, iter: 0, loss is: [0.11684053]\n",
      "epoch: 7, iter: 20, loss is: [0.06271437]\n",
      "epoch: 7, iter: 40, loss is: [0.03036864]\n",
      "epoch: 8, iter: 0, loss is: [0.16721788]\n",
      "epoch: 8, iter: 20, loss is: [0.10716369]\n",
      "epoch: 8, iter: 40, loss is: [0.21938616]\n",
      "epoch: 9, iter: 0, loss is: [0.09567357]\n",
      "epoch: 9, iter: 20, loss is: [0.06019962]\n",
      "epoch: 9, iter: 40, loss is: [0.08741301]\n"
     ]
    }
   ],
   "source": [
    "with dygraph.guard():\n",
    "    EPOCH_NUM = 10   # 设置外层循环次数\n",
    "    BATCH_SIZE = 10  # 设置batch大小\n",
    "    \n",
    "    # 定义外层循环\n",
    "    for epoch_id in range(EPOCH_NUM):\n",
    "        # 在每轮迭代开始之前，将训练数据的顺序随机的打乱\n",
    "        np.random.shuffle(training_data)\n",
    "        # 将训练数据进行拆分，每个batch包含10条数据\n",
    "        mini_batches = [training_data[k:k+BATCH_SIZE] for k in range(0, len(training_data), BATCH_SIZE)]\n",
    "        # 定义内层循环\n",
    "        for iter_id, mini_batch in enumerate(mini_batches):\n",
    "            x = np.array(mini_batch[:, :-1]).astype('float32') # 获得当前批次训练数据\n",
    "            y = np.array(mini_batch[:, -1:]).astype('float32') # 获得当前批次训练标签（真实房价）\n",
    "            # 将numpy数据转为飞桨动态图variable形式\n",
    "            house_features = dygraph.to_variable(x)\n",
    "            prices = dygraph.to_variable(y)\n",
    "            \n",
    "            # 前向计算\n",
    "            predicts = model(house_features)\n",
    "            \n",
    "            # 计算损失\n",
    "            loss = fluid.layers.square_error_cost(predicts, label=prices)\n",
    "            avg_loss = fluid.layers.mean(fluid.layers.sqrt(loss))\n",
    "            if iter_id%20==0:\n",
    "                print(\"epoch: {}, iter: {}, loss is: {}\".format(epoch_id, iter_id, avg_loss.numpy()))\n",
    "            \n",
    "            # 反向传播\n",
    "            avg_loss.backward()\n",
    "            # 最小化loss,更新参数\n",
    "            opt.minimize(avg_loss)\n",
    "            # 清除梯度\n",
    "            model.clear_gradients()\n",
    "    # 保存模型\n",
    "    fluid.save_dygraph(model.state_dict(), 'LR_model')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 5. 保存并测试模型\n",
    "\n",
    "在完成两层循环的训练过程后，将模型当前的参数（model.state_dict()）保存到文件中（通过参数指定保存的文件名 LR_model），以备预测或校验的程序调用。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "模型保存成功，模型参数保存在LR_model中\n"
     ]
    }
   ],
   "source": [
    "# 定义飞桨动态图工作环境\n",
    "with fluid.dygraph.guard():\n",
    "    # 保存模型参数，文件名为LR_model\n",
    "    fluid.save_dygraph(model.state_dict(), 'LR_model')\n",
    "    print(\"模型保存成功，模型参数保存在LR_model中\")\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "回顾下基于飞桨实现的房价预测模型，实现的效果与之前基于Python实现的模型没有区别，但两者的实现成本有天壤之别。飞桨的愿景是用户只需要了解模型的逻辑概念，不需要关心实现细节，就能搭建强大的模型。\n",
    "\n",
    "下面我们选择一条数据样本，测试下模型的预测效果。\n",
    "测试过程和在应用场景中使用模型的过程是一致的，可分成三个主要步骤。\n",
    "- 首先，配置模型预测的机器资源，本案例默认使用本机，所以无需写代码指定。\n",
    "- 其次，将训练好的模型参数加载到模型实例中，由两个语句完成，第一句是从文件中读取模型参数，第二句是将参数内容加载到模型。加载完毕后，需要将模型的状态调整为“校验”（evalueation）。这是因为训练状态的模型需要同时支持前向计算和反向传导梯度，模型的实现较为臃肿。而校验/预测状态的模型只需要支持前向计算，模型的实现更加简单，性能更好。\n",
    "- 最后，将待预测的样本特征输入到模型中，打印输出的预测结果。比较“模型预测值”和“真实房价”可见，模型预测的效果与真实房价接近。\n",
    "\n",
    "load_one_example函数实现了从数据集中抽一条样本作为测试样本。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def load_one_example(data_dir):\n",
    "    f = open(data_dir, 'r')\n",
    "    datas = f.readlines()\n",
    "    # 选择倒数第10条数据用于测试\n",
    "    tmp = datas[-10]\n",
    "    tmp = tmp.strip().split()\n",
    "    one_data = [float(v) for v in tmp]\n",
    "\n",
    "    # 对数据进行归一化处理\n",
    "    for i in range(len(one_data)-1):\n",
    "        one_data[i] = (one_data[i] - avg_values[i]) / (max_values[i] - min_values[i])\n",
    "\n",
    "    data = np.reshape(np.array(one_data[:-1]), [1, -1]).astype(np.float32)\n",
    "    label = one_data[-1]\n",
    "    return data, label"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Inference result is [[16.185738]], the corresponding label is 19.7\n"
     ]
    }
   ],
   "source": [
    "\n",
    "with dygraph.guard():\n",
    "    # 参数为保存模型参数的文件地址\n",
    "    model_dict, _ = fluid.load_dygraph('LR_model')\n",
    "    model.load_dict(model_dict)\n",
    "    model.eval()\n",
    "\n",
    "    # 参数为数据集的文件地址\n",
    "    test_data, label = load_one_example('./work/housing.data')\n",
    "    # 将数据转为动态图的variable格式\n",
    "    test_data = dygraph.to_variable(test_data)\n",
    "    results = model(test_data)\n",
    "\n",
    "    # 对结果做反归一化处理\n",
    "    results = results * (max_values[-1] - min_values[-1]) + avg_values[-1]\n",
    "    print(\"Inference result is {}, the corresponding label is {}\".format(results.numpy(), label))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "房价预测仅是一个最简单的模型，使用飞桨编写均可以事半功倍。那么，对于工业实践中更复杂的模型，使用飞桨节约的成本是不可估量的。同时，因为飞桨针对很多应用场景和机器资源做了性能优化，在功能和性能上往往强于自行编写的模型。\n",
    "\n",
    "从下一章开始，我们就将通过“手写数字识别”的案例，完整的掌握使用飞桨编写模型的方方面面。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "PaddlePaddle 1.6.0 (Python 3.5)",
   "language": "python",
   "name": "py35-paddle1.2.0"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
